﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace IRC.IRepairClouds.WebClient
{
    public static class JSONUtils
    {
        public static JavaScriptSerializer Serializer;
        public static JavaScriptSerializer SerializerWithoutType;

        static JSONUtils()
        {
            Serializer = new JavaScriptSerializer(new SimpleTypeResolver());
            SerializerWithoutType = new JavaScriptSerializer();
        }

        public static string JSON_Serialize(this object obj)
        {
            return JSON_Serialize(obj, true);
        }

        public static string JSON_Serialize(this object obj, bool enableTypeResolver)
        {
            if (enableTypeResolver)
                return Serializer.Serialize(obj);
            else
                return SerializerWithoutType.Serialize(obj);
        }

        public static T JSON_Deserialize<T>(this string json)
        {
            if (json == null)
                return default(T);
            return Serializer.Deserialize<T>(json);
        }

        public static string JSON_SerializeEx(this object obj)
        {
            try
            {
                return Serializer.Serialize(obj);
            }
            catch (Exception)
            {
                return "";
            }
        }

        public static T JSON_DeserializeEx<T>(this string json)
        {
            try
            {
                if (json == null)
                    return default(T);
                return Serializer.Deserialize<T>(json);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
    }

    public class EnumConverter<T> : JavaScriptConverter where T : struct
    {
        private Type[] _supportedTypes;
        public override IEnumerable<Type> SupportedTypes
        {
            get
            {
                if (_supportedTypes == null)
                    _supportedTypes = new Type[] { typeof(T) };
                return _supportedTypes;
            }
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Value", obj.ToString());
            return result;
        }

        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            return Enum.Parse(typeof(T), (string)dictionary["Value"]);
        }
    }
}